import 'package:collection/collection.dart';
import 'package:json_annotation/json_annotation.dart';

part 'paged_response.g.dart';

@JsonSerializable(genericArgumentFactories:true)
// 分页响应模型
class PagedResponse<T> {
  final List<T> items;
  final int total;
  final int page;
  final int perPage;
  final int? totalPages;
  PagedResponse({
    required this.items,
    required this.total,
    required this.page,
    required this.perPage,
    this.totalPages,
  });

  // 计算总页数（如果未提供）
  int get totalPagesCalculated => totalPages ?? (total / perPage).ceil();

  // 是否有下一页
  bool get hasNextPage => page < totalPagesCalculated;

  // 是否有上一页
  bool get hasPrevPage => page > 1;

  // 工厂方法：从JSON创建分页响应
  factory PagedResponse.fromJson(
      Map<String, dynamic> json,
      T Function(Object? json) fromJsonT,
      ) {
    // 处理不同的API响应格式
    dynamic itemsData = json['items'] ?? json['data'] ?? json['results'] ?? [];

    // 确保itemsData是列表
    final List<dynamic> itemsList = itemsData is List ? itemsData : [];

    return PagedResponse<T>(
      items: itemsList.map((item) => fromJsonT(item)).toList(),
      total: json['total'] ?? json['totalCount'] ?? json['count'] ?? 0,
      page: json['page'] ?? json['currentPage'] ?? 1,
      perPage: json['perPage'] ?? json['pageSize'] ?? json['limit'] ?? 10,
      totalPages: json['totalPages'] ?? json['pages'],
    );
  }

  // 转换为JSON
  // Map<String, dynamic> toJson(Object Function(T value) toJsonT) {
  //   return _$PagedResponseToJson(this, toJsonT);
  // }

  // 合并两个分页响应（用于无限滚动）
  PagedResponse<T> mergeWith(PagedResponse<T> other) {
    if (page + 1 != other.page) {
      throw ArgumentError('Cannot merge non-consecutive pages');
    }

    return PagedResponse<T>(
      items: [...items, ...other.items],
      total: other.total,
      page: other.page,
      perPage: perPage,
      totalPages: other.totalPages,
    );
  }

  // 创建空分页响应
  static PagedResponse<T> empty<T>() {
    return PagedResponse<T>(
      items: [],
      total: 0,
      page: 1,
      perPage: 10,
    );
  }

  // 创建错误分页响应
  static PagedResponse<T> error<T>(String message) {
    return PagedResponse<T>(
      items: [],
      total: 0,
      page: 1,
      perPage: 10,
    )..errorMessage = message;
  }

  // 错误消息（非标准字段，用于错误处理）
  String? errorMessage;

  // 是否为空
  bool get isEmpty => items.isEmpty;

  // 是否为错误响应
  bool get isError => errorMessage != null;

  // 当前项数
  int get itemCount => items.length;

  // 下一页页码
  int get nextPage => page + 1;

  // 上一页页码
  int get prevPage => page - 1;

  // 转换为字符串
  @override
  String toString() {
    return 'PagedResponse{items: ${items.length} items, page: $page/$totalPagesCalculated, total: $total}';
  }

  // 深度相等比较
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is PagedResponse &&
              runtimeType == other.runtimeType &&
              const DeepCollectionEquality().equals(items, other.items) &&
              total == other.total &&
              page == other.page &&
              perPage == other.perPage;

  @override
  int get hashCode =>
      const  DeepCollectionEquality().hash(items) ^
      total.hashCode ^
      page.hashCode ^
      perPage.hashCode;

}
